<!--
 * @description 新建/编辑自定义页面
 * @author dumeng
 * @date 2022/10/20
 -->
<template>
  <div class="custom-page-manage-page">
    <div class="custom-page-manage-title">新建/编辑页面</div>
    <section v-loading="submitloading" class="custom-page-manage-main">
      <el-form
        ref="form"
        v-loading="submitloading"
        :model="form"
        :rules="addRules"
        class="form"
        label-position="right"
        label-width="80px"
        style="height: 410px"
      >
        <el-form-item label="页面分类" prop="pageType">
          <el-cascader
            ref="classify"
            v-model="form.pageType"
            style="width: 100%"
            clearable
            :props="createClassifyProps"
            :options="classifyOptions"
            @change="changeClassify"
          />
        </el-form-item>
        <el-form-item label="页面名称" prop="pageName">
          <el-input v-model.trim="form.pageName" placeholder="请输入页面名称" />
        </el-form-item>

        <template v-if="$route.query.t === 'c'">
          <el-form-item label="页面标识" prop="pageDetailCode">
            <el-input
              v-if="classifyCode"
              v-model.trim="classifyCode"
              :style="{width:'30%'}"
              :disabled="true"
            />
            <el-input
              v-model.trim="form.pageDetailCode"
              :style="{width:'30%'}"
              placeholder="请输入页面标识"
              @input="handleInput"
            />
          </el-form-item>
          <el-form-item label="页面路由" prop="pageDetailRoute">
            <el-input
              v-if="pagePreRoute"
              v-model.trim="pagePreRoute"
              :style="{width:'30%'}"
              :disabled="true"
            />
            <el-input
              v-model.trim="form.pageDetailRoute"
              :style="{width:'30%'}"
              placeholder="请输入页面路由"
            />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="页面标识">
            <el-input
              v-model.trim="form.pageCode"
              :disabled="true"
              placeholder="请输入页面标识"
            />
          </el-form-item>

          <el-form-item label="页面路由">
            <el-input
              v-model.trim="form.pageRoute"
              :disabled="true"
              placeholder="请输入页面路由"
            />

          </el-form-item>

        </template>

        <el-form-item label="过渡效果" prop="transitionAnimations">
          <el-radio-group v-model="form.transitionAnimations">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否缓存" prop="isKeepAlive">
          <el-radio-group v-model="form.isKeepAlive">
            <el-radio label="0">是</el-radio>
            <el-radio label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="form.isKeepAlive === '0'"
          label="缓存方式"
          prop="keepMethod"
        >
          <el-radio-group v-model="form.keepMethod">
            <el-radio label="0">一直缓存</el-radio>
            <el-radio label="1">按页面缓存</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="form.isKeepAlive === '0' && form.keepMethod === '1'"
          label="缓存页面"
          prop="keepAliveToPage"
        >
          <el-row
            v-for="(item, index) in form.keepAliveToPage"
            :key="index"
            class="form-item-keepalive"
          >
            <el-col :span="20">
              <el-input
                v-model.trim="item.address"
                placeholder="请输入缓存页面标识"
              />
            </el-col>
            <el-col :span="4">
              <i
                v-if="form.keepAliveToPage.length > 1"
                class="el-icon-circle-close"
                @click="form.keepAliveToPage.splice(index, 1)"
              />
              <i
                v-if="index === form.keepAliveToPage.length - 1"
                class="el-icon-circle-plus-outline"
                @click="form.keepAliveToPage.push({ address: '' })"
              />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </section>
    <section class="custom-page-manage-footer">
      <el-button
        style="padding: 10px 30px"
        @click="handleCancel"
      >取 消
      </el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
  </div>
</template>

<script>
import { fetchList } from '../api/category'
import { get, insert, update } from '../api/index'
import TemplateLibIndex from '@/views/templatelib/pages'
import TemplateList from '@/views/templatelib/pages/list'

export default {
  name: 'PageManage',
  components: { TemplateList, TemplateLibIndex },
  data() {
    return {
      state: 'create',
      classifyOptions: [],
      form: {
        id: '',
        pageType: '',
        pageName: '',
        pageCode: '',
        pageRoute: '',
        isKeepAlive: '0',
        keepMethod: '0',
        transitionAnimations: '0',
        keepAliveToPage: [
          {
            address: ''
          }
        ],
        pageDetailCode: '', // 页面标识
        pageDetailRoute: '' // 页面路由
      },
      submitloading: false,
      addRules: {
        pageType: [
          { required: true, message: '请选择页面分类', trigger: 'change' }
        ],
        pageName: [
          { required: true, message: '请填写页面名称', trigger: 'blur' }
        ],
        pageDetailCode: [
          { required: true, message: '请填写页面标识', trigger: 'blur' }
        ],
        pageDetailRoute: [
          { required: true, message: '请填写页面路由', trigger: 'blur' }
        ],
        isKeepAlive: [
          { required: true, message: '请选择是否缓存', trigger: 'change' }
        ],
        keepMethod: [
          { required: true, message: '请选择缓存方式', trigger: 'change' }
        ]
      },
      // 页面格式为 ：/custom/分类标识/页面标识
      classifyCode: '', // 分类标识

      pagePreRoute: '', // 页面路由前半截不可修改部分
      createClassifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      }
    }
  },
  async created() {
    this.state = this.$route.query.t === 'u' ? 'update' : 'create'
    await this.getClassifyOption()

    // this.form.pageType = this.$route.query.c || ''
    if (this.$route.query.t === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.handleCancel()
          }
        })
      } else {
        this.getData(this.$route.query.i)
      }
    }
  },
  methods: {
    /**
     * 修改分类时
     * */
    changeClassify(e) {
      if (e.length > 0) {
        const node = this.$refs.classify.getCheckedNodes()
        const selectObj = node[0].data
        this.classifyCode = selectObj.code
        this.pagePreRoute = '/custom/' + this.classifyCode
      }
    },
    handleInput(value) {
      this.form.pageDetailRoute = '/' + value
    },
    handleCancel() {
      let selectId = ''
      if (typeof this.form.pageType !== 'string' && this.form.pageType.length > 0) {
        selectId = this.form.pageType[this.form.pageType.length - 1]
      } else {
        selectId = this.form.pageType
      }

      this.$router.replace({
        path: '/pagemanage/index',
        query: { c: selectId, s: 2 }
      })
    },
    /**
     * 获取分类
     */
    getClassifyOption() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        fetchList({ classifyType: 'FLLX_CUSTOMPAGE' })
          .then(({ data }) => {
            loading.close()
            this.classifyOptions = data.data || []
            resolve()
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    onSubmint() {
      if (this.state === 'create') {
        this.createData()
      } else {
        this.updateData()
      }
    },
    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          params.pageCode = this.classifyCode + this.form.pageDetailCode
          params.pageRoute = this.pagePreRoute + this.form.pageDetailRoute
          const arr = params.keepAliveToPage.filter((item) => {
            if (item.address) {
              return true
            }
          })
          params.keepAliveToPage = arr.map((item) => item.address).join(',')
          params['pageType'] = this.form.pageType.length > 0 
          ? this.form.pageType[this.form.pageType.length - 1] : ''
          insert(params)
            .then((res) => {
              loading.close()
              this.$message.success('创建成功！')
              this.handleCancel()
              // eslint-disable-next-line handle-callback-err
            })
            .catch((err) => {
              loading.close()
            })
        }
      })
    },
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          // params.keepAliveToPage = params.keepAliveToPage.map(item => item.address).join(',')
          const arr = params.keepAliveToPage.filter((item) => {
            if (item.address) {
              return true
            }
          })
          params.keepAliveToPage = arr.map((item) => item.address).join(',')
          params['insertRecode'] = 'update'
          let selectId = ''

          if (typeof this.form.pageType !== 'string' && this.form.pageType.length > 0) {
            selectId = this.form.pageType[this.form.pageType.length - 1]
          } else {
            selectId = this.form.pageType
          }
          params['pageType'] = selectId
          update(params)
            .then((res) => {
              loading.close()
              this.$message.success('编辑成功！')
              this.handleCancel()
            })
          // eslint-disable-next-line handle-callback-err
            .catch((err) => {
              loading.close()
            })
        }
      })
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id })
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              if (key === 'keepAliveToPage') {
                if (data[key]) {
                  this.form[key] = data[key].split(',').map((item) => {
                    return { address: item }
                  })
                } else {
                  this.form[key] = [
                    {
                      address: ''
                    }
                  ]
                }
              } else if (key === 'pageType') {
                const idsArr =
                      (data.pageTypeIds &&
                          data.pageTypeIds.split(',')) ||
                      []
                this.form[key] = idsArr
              } else {
                this.form[key] = data[key]
              }
            }
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    }
  }
}
</script>

<style lang="scss">
.custom-page-manage-page {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .custom-page-manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: "";
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .custom-page-manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: auto;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .form-item-keepalive {
        margin-bottom: 10px;

        .el-icon-circle-close,
        .el-icon-circle-plus-outline {
          font-size: 20px;
          color: #999;
          margin-left: 10px;
          cursor: pointer;
        }
      }
    }
  }

  .custom-page-manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
